package com.td.lib.viewmodel;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.Lifecycle;
import ohos.aafwk.ability.LifecycleStateObserver;
import ohos.aafwk.content.Intent;
import ohos.utils.PacMap;

/**
 * ViewModelAbility
 *
 * @since 2021/10/14
 */
public abstract class ViewModelAbility extends Ability implements ViewModelStoreOwner {
    static final class NonConfigurationInstances {
        Object custom;
        ViewModelStore viewModelStore;
    }

    private NonConfigurationInstances mNonConfigurationInstances;
    private boolean mChangingConfigurations;


    public ViewModelAbility() {
        getLifecycle().addObserver(new LifecycleStateObserver() {
            @Override
            public void onStateChanged(Lifecycle.Event event, Intent intent) {
                if (event == Lifecycle.Event.ON_STOP) {
                    if (!mChangingConfigurations) {
                        getViewModelStore().clear();
                    }
                }
            }
        });
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        mChangingConfigurations = false;
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        mChangingConfigurations = true;
    }

    @Override
    public Object onStoreDataWhenConfigChange() {
        if (mNonConfigurationInstances == null) {
            mNonConfigurationInstances = new NonConfigurationInstances();
        }
        return mNonConfigurationInstances;
    }

    @Override
    public ViewModelStore getViewModelStore() {
        if (mNonConfigurationInstances == null) {
            Object object = getLastStoredDataWhenConfigChanged();
            if (object == null) {
                mNonConfigurationInstances = new NonConfigurationInstances();
            } else if (object instanceof NonConfigurationInstances) {
                mNonConfigurationInstances = (NonConfigurationInstances) object;
            } else {
                throw new IllegalArgumentException("getLastStoredDataWhenConfigChanged must be NonConfigurationInstances");
            }
        }
        if (mNonConfigurationInstances.viewModelStore == null) {
            mNonConfigurationInstances.viewModelStore = new ViewModelStore();
        }
        return mNonConfigurationInstances.viewModelStore;
    }
}
